import time
import random

import requests
from datetime import datetime
from feapder.db.redisdb import RedisDB
redis_conn = RedisDB(ip_ports='124.222.45.213' + ':' + '6379', db=7,
                     user_pass="8mkfmskwbwjez3fc")


class ProxyMiddlewares():
    def __init__(self):
        self.ip_list = list()

    def add_ips(self):
        headers = {
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
        }

        params = (
            ('key', 'T8R0DFJ5'),
            ('num', '1'),
            ('area', ''),
            ('isp', ''),
            ('format', 'json'),
            ('seq', ''),
            ('pwd', 'B14B0C5BAFB5'),
        )

        response = requests.get('https://overseas.proxy.qg.net/get', headers=headers, params=params)

        for res in response.json()['data']:
            ips = res['server']
            self.ip_list.append(ips)

    # add_ips()
    def remove_ips(self, ips):
        self.ip_list.remove(ips)

    def get_ips(self):
        proxy_list_length = len(self.ip_list)
        try:
            redis_proxy_number = redis_conn.incr('ips_pool', 1)
        except:
            redis_proxy_number = random.randint(0, proxy_list_length - 1)
        distributed_number = redis_proxy_number % proxy_list_length
        proxy_info = self.ip_list[distributed_number]
        proxies = {
            'http': 'http://T8R0DFJ5:B14B0C5BAFB5@{}'.format(proxy_info),
            'https': 'http://T8R0DFJ5:B14B0C5BAFB5@{}'.format(proxy_info)
        }
        return proxies, proxy_info

    def test_ips(self):
        proxies, ips = self.get_ips()
        print(proxies)
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
        }
        try:
            response = requests.get('https://www.baidu.com/', headers=headers, proxies=proxies, timeout=(15, 15),
                                    verify=False)
            if response.status_code == 200:
                print(f'代理 {ips} 正常,   时间:{str(datetime.now())}')
        except Exception as e:
            if 'Caused by ConnectTimeoutError' in str(e):
                error_msg = '代理服务超时'
            elif 'Read timed out' in str(e) or 'Cannot connect to proxy' in str(e):
                error_msg = '请求目标网站超时'
            elif 'Expecting value' in str(e):
                error_msg = '疑似无法访问国际网站'
            else:
                error_msg = str(e)
            print(f'代理 {ips} 错误,  时间:{str(datetime.now())} 错误信息:{error_msg}', )
            self.remove_ips(ips)


if __name__ == '__main__':
    s = ProxyMiddlewares()
    s.add_ips()
    s.test_ips()
